<template>
  <div class="app-container">
    <y-table ref="gridRef" v-bind="listOptions" @toolbar-button-click="toolbarButtonClickEvent">
      <template #editcolumn="{ row, column }">
        <div v-if="!editColumnFlag">
          <el-input size="mini" v-model="row[column.field]" @change="updateById(row, column)"></el-input>
        </div>
        <div v-else>
          {{ column.field === 'isValid' ? row[column.field] ? '是' : '否' : row[column.field] }}
        </div>
      </template>
    </y-table>
    <y-form-dialog :title="formOptions.title" ref="dialogFormRef" :form-options="formOptions"
      @confirm="confirmForm"></y-form-dialog>
    <y-form-dialog :title="formOptions.title" ref="dialogInfoRef" :form-options="detailFormConfig"
      @confirm="_ => { }"></y-form-dialog>
  </div>
</template>

<script>

import {
  getMajorList, updateMajorField, bathDeleteMajor, addMajor,
  getMajorClassCodeList, checkCodeRepeat, createMajorCode,
  getClassMajorByEduLevel, getMajorClassBySubject, getStandardCodeList
} from '@/api/base/major' // 接口

import listMixin from '@/mixins/listMixin'

export default {
  mixins: [listMixin],
  data() {
    return {
      //编辑模式开关
      editColumnFlag: true,
      //是否教学单位
      options: [
        { value: 1, label: '是' },
        { value: 0, label: '否' }
      ],
      // 表格配置
      listOptions: {
        // 导出
        exportConfig: { fileName: '专业信息导出', moudle: 'ZYXXDC' },
        // 导入
        importConfig: { fileName: '专业信息导入', module: 'ZYXXDR' },
        // 默认查询数据
        defaultQueryData: {
          // form
          form: {},
          // 分页
          page: {
            pageSize: 50
          },
          // 其他查询参数
          params: {}
        },
        // 获取数据方法
        dataMethod: getMajorList,
        // 表格配置
        tableOptions: {
          rowConfig: {
            keyField: 'tid'
          },
          toolbarConfig: {
            // 按钮组
            buttons: [
              { name: '新增', code: 'add', status: 'primary', icon: 'vxe-icon-add' },
              { name: '开启编辑模式', code: 'openEdit', status: 'primary', icon: 'vxe-icon-add' },
              { name: '关闭编辑模式', code: 'closeEdit', status: 'primary', icon: 'vxe-icon-add' },
              { name: '批量删除', code: 'batchDelete', status: 'danger', icon: 'vxe-icon-delete' },
              { name: '专业门类', code: 'toMajorSubjectPage', status: 'primary', icon: 'vxe-icon-add' },
              { name: '专业类', code: 'toMajorClass', status: 'primary', icon: 'vxe-icon-add' },
              { name: '专业国标库', code: 'toMajorStandard', status: 'primary', icon: 'vxe-icon-add' }
            ],
            // 工具栏
            tools: [
              // { type: 'button', code: 'DivCode', icon: 'vxe-icon-edit', circle: true },
            ]
          },
          // 表格列
          columns: [
            { type: 'checkbox', width: 48, align: 'center', fixed: 'left' },
            { type: 'seq', width: 48, align: 'center', fixed: 'left' },
            { field: "collegeCode", minWidth: 120, title: "所属院系名称", dictCode: 'college_list' },
            { field: "majorCode", width: 80, title: "专业代码" },
            { field: "majorName", minWidth: 180, title: "专业名称", slots: { default: "editcolumn" } },
            { field: "majorTitleEn", minWidth: 150, title: "专业英文名称", visible: false },
            { field: "parentMajorCode", minWidth: 80, title: "所属父专业代码", visible: false },
            { field: "schoolingLen", width: 80, title: "学制", slots: { default: "editcolumn" } },
            { field: "majorSubjectCode", width: 100, title: "所属门类", slots: { default: "editcolumn" } },
            { field: "majorClassCode", minWidth: 120, title: "所属专业类", slots: { default: "editcolumn" } },
            { field: "standardCode", width: 100, title: "国标专业代码", slots: { default: "editcolumn" } },
            { field: "standardName", minWidth: 120, title: "国标专业名称", slots: { default: "editcolumn" } },
            { field: "degreeType", width: 100, title: "授位类别", slots: { default: "editcolumn" } },
            { field: "degreeTypeEn", minWidth: 150, title: "授位类别英文", visible: false },
            { field: "eduLevelCode", minWidth: 80, title: "培养层次", dictCode: "education_level", visible: false },
            { field: "eduBkgdLevelCode", minWidth: 80, title: "学历层次", dictCode: 'education_background_level', visible: false },
            { field: "buildTime", minWidth: 120, title: "建立年月", visible: false },
            { field: "startTerm", minWidth: 120, title: "开始招生学期", dictCode: "term_list", visible: false },
            { field: "majorIntro", minWidth: 150, title: "专业简介备注", visible: false },
            { field: "isValid", width: 100, title: "启停状态", slots: { default: "editcolumn" } },
            {
              title: '操作',
              width: 130,
              cellRender: {
                name: 'buttons',
                options: [
                  { content: '修改', name: 'edit' },
                  {
                    content: '更多', dropdowns: [
                      { content: '详情', name: 'info' },
                      { content: '删除', name: 'delete' }
                    ]
                  }
                ],
                events: {
                  click: ({ name, row }) => {
                    switch (name) {
                      case 'edit':
                        this.openFormDialog({ row, refName: 'dialogFormRef' })
                        break
                      case 'delete':
                        this.deleteRow({ row, deleteMethod: (row) => this.bathDeleteMajor(row.tid) })
                        break
                      case 'info':
                        this.openFormDialog({ row, refName: 'dialogInfoRef' })
                        break
                      default:
                        break
                    }
                  }
                }
              }
            }
          ]
        },
        // 表单配置
        formOptions: {
          items: [
            {
              field: 'collegeCode', title: '院所名称',
              itemRender: {
                name: 'ZSelect',
                props: {
                  dictCode: 'college_list_easy'
                }
              }
            },
            {
              field: 'majorSubjectCode', title: '所属门类',
              cascader: ['majorClassCode'],
              itemRender: {
                name: 'ZSelect',
                props: {
                  dictCode: 'major_subject'
                }
              }
            },
            {
              field: "majorClassCode", title: "所属专业类",
              cascader: ["standardCode"],
              itemRender: {
                name: 'ZSelect',
                props: {
                  initData: async (formData) => {
                    if (formData.majorSubjectCode) {
                      return await getMajorClassCodeList(formData.majorSubjectCode)
                    } else {
                      return await this.getDictItems("major_class")
                    }
                  },
                }
              }
            },
            {
              field: "standardCode", title: "国际专业名称",
              itemRender: {
                name: 'ZSelect',
                props: {
                  initData: async (formData) => {
                    if (formData.majorSubjectCode && formData.majorClassCode) {
                      return await getStandardCodeList(formData.majorSubjectCode, formData.majorClassCode)
                    } else {
                      return await this.getDictItems("major_standard");
                    }
                  }
                }
              }
            },
            {
              field: 'isValid', title: '启停状态',
              itemRender: {
                name: 'ZSelect',
                props: {
                  initData: async () => [
                    { name: '启用', value: "1" },
                    { name: '停用', value: "0" },
                  ]
                }
              }
            },
            {
              field: 'keywords', title: '专业代码|名称',
              itemRender: {
                name: 'VxeInput'
              }
            }
          ]
        },
      },
      formOptions: {
        title: '专业信息',
        titleWidth: 140,
        items: [
          {
            required: true, field: 'collegeCode', title: '院所名称',
            itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'college_list_easy'
              }
            }
          },
          {
            required: true, field: 'majorCode', span: 12, title: '专业代码',
            itemRender: {
              name: 'VxeInput',
              events: {
                click: (slotParams, { name }) => {
                  if (name === 'majorCode'
                    && !slotParams.data.tid
                    && slotParams.data.majorCode) {
                    checkCodeRepeat(slotParams.data.majorCode).then(res => {
                      if (res.status) {
                        this.$set(slotParams.data, 'majorCode', "")
                      }
                    })
                  }
                }
              }
            }
          },
          {
            field: 'autoMajorCode', span: 12,
            itemRender: {
              name: 'VxeButtonGroup',
              options: [
                { name: 'autoMajorCode', content: '系统自动生成', status: 'primary' }
              ],
              events: {
                click: (slotParams, { name }) => {
                  if (name === 'autoMajorCode'
                    && !slotParams.data.tid
                    && slotParams.data.collegeCode) {
                    createMajorCode(slotParams.data.collegeCode).then(res => {
                      if (res.status) {
                        this.$set(slotParams.data, 'majorCode', res.data)
                      }
                    })
                  }
                }
              }
            }
          },
          {
            required: true, field: "majorName", span: 12, title: "专业名称", itemRender: {
              name: 'VxeInput'
            }
          },
          {
            field: "majorNameEn", title: "专业英文名称", span: 12, itemRender: {
              name: 'VxeInput'
            }
          },
          {
            field: "isParentMajor", title: "是否大类专业", span: 12, itemRender: {
              name: 'VxeSwitch'
            }
          },
          {
            field: "parentMajorCode", title: "所属大类专业", span: 12, itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'parent_major_list'
              }
            }
          },
          {
            required: true, field: "eduLevelCode", title: "培养层次", span: 12,
            cascader: ['majorSubjectCode'], itemRender: {
              name: "ZSelect",
              props: {
                dictCode: 'education_level'
              }
            }
          },
          {
            required: true, field: "majorSubjectCode", title: "所属门类", span: 12,
            cascader: ['majorClassCode'], itemRender: {
              name: "ZSelect",
              props: {
                initData: (formData) => {
                  if (formData.eduLevelCode) {
                    return getClassMajorByEduLevel(formData.eduLevelCode)
                  } else {
                    return []
                  }
                },
              }
            }
          },
          {
            required: true, field: "majorClassCode", title: "所属专业类", span: 12,
            cascader: ['standardCode'], itemRender: {
              name: "ZSelect",
              props: {
                initData: async (formData) => {
                  if (formData.majorSubjectCode) {
                    return getMajorClassBySubject(formData.majorSubjectCode)
                  } else {
                    return []
                  }
                },
              }
            }
          },
          {
            required: true, field: "standardCode", title: "国际专业", span: 12, itemRender: {
              name: "ZSelect",
              props: {
                bounds: 'standardName',
                initData: async (formData) => {
                  if (formData.majorClassCode) {
                    return getStandardCodeList(formData.majorSubjectCode, formData.majorClassCode)
                  } else {
                    return []
                  }
                }
              }
            }
          },
          {
            required: true, field: "schoolingLen", title: "学制", span: 12, itemRender: {
              name: "ZSelect",
              props: {
                initData: async () => {
                  return [
                    { name: 1, value: 1 },
                    { name: 2, value: 2 },
                    { name: 3, value: 3 },
                    { name: 4, value: 4 },
                    { name: 5, value: 5 },
                  ]
                }
              }
            }
          },
          {
            field: "degreeType", title: "授位类别", span: 12, itemRender: {
              name: "ZSelect",
              props: {
                dictCode: 'degree_type'
              }
            }
          },
          {
            field: "degreeTypeEn", title: "授位类别英文", span: 12, itemRender: {
              name: 'VxeInput'
            },
          },
          {
            field: "eduBkgdLevelCode", title: "学历层次", span: 12, itemRender: {
              name: "ZSelect",
              props: {
                dictCode: 'education_background_level'
              }
            }
          },
          {
            field: 'buildTime', span: 12, title: '建立年月',
            itemRender: {
              name: 'VxeInput',
              props: {
                type: 'month',
                valueFormat: 'yyyyMM',
                labelFormat: 'yyyyMM'
              }
            }
          },
          {
            field: 'startTerm', title: '开始招生学期', span: 12, itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'term_list'
              }
            }
          },
          {
            required: true, field: 'isValid', title: '启停状态',
            itemRender: {
              name: 'ZSelect',
              props: {
                type: 'radio',
                initData: async () => [
                  { name: '启用', value: 1 },
                  { name: '停用', value: 0 },
                ]
              }
            }
          },
          {
            field: 'majorIntro', title: '专业简介备注', itemRender: {
              name: 'VxeTextarea',
            },
            rules: [{
              max: 1000,
              message: '请限制在1000字内'
            }]
          },
        ]
      },
    }
  },
  computed: {
    detailFormConfig() {
      return {
        ...this.formOptions,
        border: true,
        items: this.formOptions.items.filter(d => d.field).map(({ field, title }) => {
          return { field, title }
        })
      }
    }
  },
  /**
   * 组件挂载时异步执行的方法
   */
  async mounted() {
    // 动态设置查询参数
    // 此处的目的是根据某些条件或逻辑动态地设置组件的查询参数，以便在加载数据前做好准备
    await this.setFormQuery()

    // 加载数据
    // 通过refs引用调用loadData方法来加载数据
    this.$refs.gridRef.loadData()
  },
  methods: {
    /**
     * 工具栏按钮点击事件处理函数
     * @param {Object} event - 事件对象，包含按钮代码
     * 该函数根据点击的工具栏按钮代码，执行不同的操作
     */
    toolbarButtonClickEvent({ code }) {
      switch (code) {
        case 'openEdit':
          // 打开编辑模式
          this.editColumnFlag = false
          break
        case 'closeEdit':
          // 关闭编辑模式
          this.editColumnFlag = true
          break
        case 'add':
          // 执行添加操作，打开表单对话框
          this.openFormDialog({ row: null, refName: 'dialogFormRef' })
          break
        case 'batchDelete':
          // 批量删除
          let checkboxRecords = this.getCheckboxRow()
          if (checkboxRecords.length === 0) {
            this.$message.warning('请先选择要删除的记录')
            return
          }
          this.$confirm('确认删除选中的记录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteById(checkboxRecords)
          })
          break
        default:
          break
      }
    },
    //提交表单
    async confirmForm(form) {
      return new Promise((resolve, reject) => {
        this.saveOrUpdate(form).then(res => {
          if (res.status) {
            this.$message.success(res.message)
            this.$refs.gridRef.loadData()
            resolve(true)
          }
        })
      })
    },
    // 保存或修改
    saveOrUpdate(form) {
      if (form.tid) {
        return updateMajorField(form)
      } else {
        return addMajor(form)
      }
    },
    // 修改
    updateById(row) {
      updateMajorField(row).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    // 删除
    deleteById(row) {
      bathDeleteMajor(row.tid || row.map(item => item.tid).join(',')).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    async setFormQuery() {
      // this.listOptions.defaultQueryData.form.pageSize = 50
      // this.listOptions.defaultQueryData.form.pageNum = 1
    },
    getRadioRow() {
      return this.$refs.gridRef.$refs.gridRef.getRadioRecord()
    },
    getCheckboxRow() {
      return this.$refs.gridRef.$refs.gridRef.getCheckboxRecords()
    },
  }
}
</script>

<style lang="scss" scoped></style>
